<?php

namespace app\common\model\mall\shop;

use think\Model;

class Freight extends Model
{
    // 表名
    protected $name = 'mall_shop_freight';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'method_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }
    
    public function getMethodList()
    {
        return ['2' => __('Method 2'), '3' => __('Method 3')];
    }

    public function getMethodTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['method']) ? $data['method'] : '');
        $list = $this->getMethodList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function price()
    {
        return $this->hasMany('\app\common\mode\mall\shop\Freightprice', "freight_id", "id");
    }

    /**
     * 店铺运费（自动取店铺默认运费）
     * @param @shop_ids 店铺ID（始发地）
     * @param int $cityId 目的地
     * @param int $freighttype 计费方式（2=按重,3=按件）
     * @param int $goods_total_weight 商品总重(如果$freighttype=3,则为总件数)
     */
    public static function shopFreight($shop_id, $cityId, $freighttype=2, $goods_total_weight=1){
        $default = \app\common\model\mall\shop\Shop::getFieldById($shop_id,'freight');
        $expressPrice = self::orderFreight($shop_id, $cityId, $freighttype, $goods_total_weight);
        return (int)((int)$expressPrice>0) ? $expressPrice : $default;
    }

    /**
     * 订单运费
     * @param @shop_ids 店铺ID（始发地）
     * @param int $cityId 目的地
     * @param int $freighttype 计费方式（2=按重,3=按件）
     * @param int $goods_total_weight 商品总重(如果$freighttype=3,则为总件数)
     */
    public static function orderFreight($shop_id, $cityId, $freighttype=2, $goods_total_weight=1){
        $shopFreight = self::where(["shop_id"=>$shop_id,"method"=>$freighttype])->find();
        $expressPrice = 0;
        if(!empty($shopFreight))
            $expressPrice = $shopFreight->calcFee($freighttype, $goods_total_weight, $cityId);
        return $expressPrice;
    }
    /**
     * 运费计算
     * @param int $goods_total_weight 商品总重（或总件数）
     * @param int $cityId 目的地
     */
    public function calcFee($total_weight, $city_id)
    {
        $price = [];  // 当前规则
        foreach ($this['price'] as $item) {
            $areaModel = model("app\common\model\mall\oper\Area");
            $areaChildIds = $areaModel->getChildIds($item['region_data']);
            if ($item['region_data'] == "*" || in_array($city_id, $areaChildIds)) {
                $price = $item;
                break;
            } else {
                return 0;
            }
        }
        //没超过$price['first']
        if ($total_weight <= $price['first']) {
            return number_format($price['first_fee'], 2);
        }
        // 续件or续重 数量
        $additional = $total_weight - $price['first'];
        // 计算续重/件金额
        //没超过$price['additional']
        if ($additional <= $price['additional']) {
            return number_format($price['first_fee'] + $price['additional_fee'], 2);
        }else {//没超过$price['additional']
            $additionalFee = bcdiv($price['additional_fee'], $price['additional'], 2) * $additional;
            return number_format($price['first_fee'] + $additionalFee, 2);
        }

    }

}
